package userrolelogic

import (
	"common/comCopier"
	"common/dao/model"
	"common/utils"
	"context"
	"errors"
	"gorm.io/gorm"
	"time"

	"OemServer/internal/svc"
	"OemServer/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *pb.UserRole) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.RoleName == "" {
		return nil, errors.New("roleName is null")
	}
	if in.RoleDescribe == "" {
		return nil, errors.New("roleDescribe is null")
	}
	if in.RolePermissions == "" {
		return nil, errors.New("rolePermissions is null")
	}
	if in.RoleStatus == 0 {
		return nil, errors.New("RoomStatus is type 1 or 2")
	}

	var (
		UserRole = model.UserRole{}
	)

	if err := comCopier.CopyWithOption(&UserRole, in); err != nil {
		return nil, err
	}
	UserRole.UUID = utils.GetUuid()
	t := time.Now()
	UserRole.CreateTime = &t
	UserRole.RoleStatus = 1
	db := l.svcCtx.DB
	table := db.Table(model.TableNameUserRole)
	err := table.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(&UserRole).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}
